<template>
  <el-select
    v-model="value"
    :multiple="multiple"
    :disabled="disabled"
    collapse-tags
    :clearable="clearable"
    filterable
    :placeholder="placeholder"
    @change="onChange"
    @focus="onFocus"
  >
    <el-option
      v-for="(item, index) in Options"
      :key="index"
      :label="item.label"
      :value="item.value"
    >
      <div class="single-model" @click="selectStages(item.value)" >
        <div>
          <xdrdirselector Width="60px" Height="60px" :showlist="item.item"></xdrdirselector>
        </div>
        <div>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.label }}</span>
        </div>
      </div>
    </el-option>
  </el-select>
</template>
<script>
import { getTscControl } from '../../api/control'
import { uploadSingleTscParam } from '../../api/param'
import { getMessageByCode } from '../../utils/responseMessage'
import xdrdirselector from '../../components/XRDDirSelector/index.vue'
import PhaseDataModel from 'openatc-components/package/kisscomps/components/IntersectionMap/crossDirection/utils'
import { getDirName } from './utils.js'
import { getTheme } from '../../utils/auth'
export default {
  name: 'SelectCrossPhase',
  components: {
    xdrdirselector
  },
  props: {
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: ''
    },
    bizType: {
      type: String,
      default: ''
    },
    agentid: {
      type: String,
      default: '10501'
    },
    clearable: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      list: [],
      value: [],
      Options: [],
      phaseList: [],
      sidewalkPhaseData: []
    }
  },
  watch: {
    agentid (val) {
      this.value = ''
      this.Options = []
      // this.onLoad()
    }
  },
  created () {
    // this.onLoad()
    this.PhaseDataModel = new PhaseDataModel()
    // this.CrossDiagramMgr = new CrossDiagramMgr()
    if (!this.placeholder) {
      this.placeholder = this.$t('openatc.bottleneckcontrol.phaseid')
    }
  },
  methods: {
    onFocus () {
      if (!this.Options || this.Options.length === 0) {
        this.onLoad()
      }
    },
    onLoad () {
      this.getPhase()
      // this.initData()
    },
    setOption (list) {
      let color = getTheme() === 'light' ? '#1E1E1E' : '#F1F3F4'
      this.Options = list.map((item, index) => {
        let dirArr = []
        for (let rec of item.direction) {
          let recd = {
            id: rec,
            peddirection: this.getPed(item.peddirection),
            color: color
          }
          dirArr.push(recd)
        }
        let nameArr = getDirName(dirArr)
        let name = ''
        nameArr = nameArr.map(record => this.$t(record))
        name = nameArr.join(',')
        if (this.bizType) {
          // name = this.$t('openatc.greenwaveoptimize.phase') + item.id + ' ' + name
          name = this.$t('openatc.greenwaveoptimize.phase') + item.id + ' ' + name
        }
        console.log(dirArr, 'dirArr')
        // console.log(nameArr, 'nameArr')
        return {
          label: name,
          item: dirArr,
          value: item.id
        }
      })
    },
    onChange (value) {
      let option = this.Options.filter(item => item.value === value)[0]
      this.$emit('onChange', value, option, this.agentid, this.bizType)
    },
    selectStages (value) {
      this.$emit('selectStages', value)
    },
    getPhase () {
      let type = 'phase'
      let agentid = this.agentid
      uploadSingleTscParam(type, agentid).then(data => {
        let res = data.data
        if (!res.success) {
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.$message.error(parrenterror)
          }
          return
        }
        this.phaseList = res.data.data.phaseList
        this.getPedPhasePos(this.phaseList)
        this.setOption(this.phaseList)
      })
    },
    initData () {
      let agentId = this.agentid
      getTscControl(agentId).then((data) => {
        if (!data.data.success) {
          if (data.data.code === '4003') {
            this.devStatus = 2
            this.$message.error(this.$t('edge.errorTip.devicenotonline'))
            return
          }
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        let TscData = JSON.parse(JSON.stringify(data.data.data.data))
        this.handleStageData(TscData) // 处理阶段（驻留）stage数据
      }).catch(error => {
        this.$message.error(error)
        console.log(error)
      })
    },
    // handleStageData (data) {
    //   if (!data) return
    //   let peddirections = this.getPed(data)
    //   let stagesTemp = []
    //   let tempList = []
    //   for (let stg of data) {
    //     let directionList = []
    //     let currPhase = this.phaseList.filter((item) => {
    //       return item.id === stg
    //     })[0]
    //     if (currPhase !== undefined) {
    //       directionList.push(...currPhase.direction)
    //       directionList = Array.from(new Set(directionList))
    //     }
    //     if (directionList.length === 0) {
    //       tempList.push({
    //         id: '',
    //         color: '#454545',
    //         peddirection: peddirections
    //       })
    //     } else {
    //       tempList = directionList.map(dir => ({
    //         id: dir,
    //         color: '#454545',
    //         peddirection: peddirections
    //       }))
    //     }
    //     let newTemp = tempList.filter(item => item.id !== '')
    //     stagesTemp.push(...newTemp)
    //   }
    //   return stagesTemp
    // },
    getPed (data) {
      let ped = []
      let peddirections = []
      for (let walk of this.sidewalkPhaseData) {
        for (let ped of data) {
          let objs = {}
          objs.name = walk.name
          objs.id = walk.id
          if (ped === walk.id) {
            peddirections.push(objs)
            peddirections = Array.from(new Set(peddirections))
          }
        }
      }
      ped.push(...peddirections)
      console.log(ped, 'pedped')
      return ped
    },
    getPedPhasePos (phaseList) {
      // 行人相位信息
      this.sidewalkPhaseData = []
      console.log(phaseList, 'this.this.phaseList')
      phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
          // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.sidewalkPhaseData.push({
                // key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              })
            }
          })
        }
      })
      return this.sidewalkPhaseData
    },
    handleStageData (data) {
      this.stagesList = []
      let stages = data.stages
      for (let stage of stages) {
        let tempList = []
        let directionList = []
        for (let stg of stage) {
          let currPhase = this.phaseList.filter((item) => {
            return item.id === stg
          })[0]
          if (currPhase !== undefined) {
            directionList = [...currPhase.direction, ...directionList]
          }
          // directionList = [...currPhase.direction, ...directionList]
        }
        directionList = [...new Set(directionList)]
        tempList = directionList.map(dir => ({
          id: dir,
          color: '#606266'
        }))
        this.stagesList.push(tempList)
      }
      this.list = this.stagesList
      // this.setOption()
    },
    init (val) {
      let target = val
      if (this.multiple) {
        target = [val]
      }
      this.value = target
    },
    getNameById (id) {
      let res = ''
      for (const item of this.Options) {
        if (id === item.agentid) {
          res = item.name
          break
        }
      }
      return res
    }
  }
}
</script>
<style scoped>
.single-model {
  width: 110%;
  display: flex;
  justify-content: space-between;
}
</style>
